package net.sansi.v3correctserver.service.correct;

import lombok.extern.slf4j.Slf4j;
import net.sansi.v3correctserver.config.matrixloader.DoubleMatrixFileLoader;
import net.sansi.v3correctserver.constenum.AppHelper;
import net.sansi.v3correctserver.dto.correct.BrightCorrectDto;
import net.sansi.v3correctserver.entity.screen.CorrectArea;
import net.sansi.v3correctserver.entity.space.CorrectCnf;
import net.sansi.v3correctserver.service.space.ProjectSpace;
import net.sansi.v3correctserver.task.BrightCorrectTask;
import net.sansi.v3correctserver.task.BrightCorrectTaskMock;
import net.sansi.v3correctserver.util.Matrix;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Fang
 * create time : 2024/11/1
 * IDE : IntelliJ IDEA
 */
@Service
@Slf4j
public class BrightCorrectService {


    /**
     * 启动亮度矫正任务
     *
     * @param form 请求
     * @return 任务id
     */
    public String startTask(BrightCorrectDto.RectStartReq form) {
        CorrectCnf correctCnf = AppHelper.projectSpace().getCorrectCnf();
        List<Double> tBrights = form.getTargetPhotoBright();

        //TODO 实际上机测试需要切换回  BrightCorrectTask
        BrightCorrectTaskMock task = new BrightCorrectTaskMock(
                new BrightCorrectTask.Params()
                        .setFence(form.getFence())
                        .setArea(correctCnf.getArea(form.getAreaId()))
                        .setTargetPhotoBright(
                                tBrights == null ?
                                        new double[]{-1, -1, -1} :
                                        new double[]{tBrights.get(0), tBrights.get(1), tBrights.get(2)}
                        )
        );
        AppHelper.getTaskManager().addTask(task, true);
        return task.getTaskId();
    }

    /**
     * 加载亮度矫正结果
     *
     * @param area 区域
     * @return 亮度矫正结果 [r,g,b]
     */
    public List<Matrix<Double>> loadCorrectResult(CorrectArea area) {
        ProjectSpace projectSpace = AppHelper.projectSpace();
        List<Matrix<Double>> res = new ArrayList<>();
        int w = area.getShowArea().getWidth(), h = area.getShowArea().getHeight();
        for (int i = 0; i < 3; i++) {
            Path path = projectSpace.brightResult(area.getAreaId(), i);
            if (!path.toFile().exists()) {
                log.info("亮度矫正结果不存在 [path] {}", path.toAbsolutePath());
                res.add(new Matrix<>(w, h, (x, y) -> 0.0));
                continue;
            }
            Matrix<Double> result = Matrix.load(new DoubleMatrixFileLoader(), path);
            if (result.getWidth() != w || result.getHeight() != h) {
                log.info("亮度矫正结果尺寸不匹配 [path] {}", path.toAbsolutePath());
                res.add(new Matrix<>(w, h, (x, y) -> 0.0));
                continue;
            }
            res.add(result);
        }
        return res;
    }

}
